﻿using DocumentFormat.OpenXml.Lite.Core;
using DocumentFormat.OpenXml.Lite.Helper;
using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.WordprocessingML.Word.Base
{
    [XmlRoot("sectPr", Namespace = Constants.WordMain)]
    public class SectionProperty : XmlSerializable, IParagraphPropElement
    {
        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        [Optional]
        [XmlElement("", Namespace = Constants.WordMain)]
        public XmlList<ISectionPropElement> Elements { get; set; }

        public SectionProperty()
        {
            Elements = new XmlList<ISectionPropElement>();
            Elements.Changing += SectionProperties_Changing;
        }

        void SectionProperties_Changing(object sender, ListEventArgs<ISectionPropElement> args)
        {
            if (args.Type == ListEventType.Remove)
                return;

            foreach (var obj in args.Objects)
            {
                if (obj.GetType().IsInheritedFrom(typeof(ISectionPropElement)))
                {
                    var element = Elements.FirstOrDefault(e => e.GetType() == obj.GetType());
                    if (obj != null)
                    {
                        throw new OpenXmlException("Element with the same type (" +
                            element.GetType().ToString() + ") already added to list: " + Elements.ToString());
                    }
                }
            }
        }

        public void Copy(object obj)
        {
            if (obj is SectionProperty)
            {
                this.Elements = (obj as SectionProperty).Elements;
            }
        }
    }
}
